package com.ding.courier;

import com.ding.common.*;

import java.io.IOException;
import java.net.Socket;
import java.util.logging.Logger;

public class CPool extends Pool {

    private String targetHost;
    private int targetPort;

    public int getTargetPort() {
        return targetPort;
    }

    public String getTargetHost() {
        return targetHost;
    }

    public void setTargetHost(String targetHost) {
        this.targetHost = targetHost;
    }

    public void setTargetPort(int targetPort) {
        this.targetPort = targetPort;
    }

    private Logger logger = Logger.getLogger("");
    private CommanderHolder commanderHolder;

    public void setCommanderHolder(CommanderHolder commanderHolder) {
        this.commanderHolder = commanderHolder;
    }

    public void addOne(StreamChannel socketHolder) {

        Repeater repeater = new Repeater();
        repeater.setLeft(socketHolder);

        //当关闭自身的时候
        socketHolder.setAfterCloseStrategy(() -> {
            logger.info("流通道关闭");
            if (repeater.getRight() != null) {
                repeater.getRight().close(true);
            }
        });

        //另一侧节点被关闭的时候是无法进行判断的
        socketHolder.setAfterCloseAnotherStrategy(() -> {//被动回收另一侧节点
            if (!socketHolder.isClosed()) {
                logger.info("回收目标通道");
                commanderHolder.sendMsg(new Message().type(Constant.RECYCLE_PASSIVITY).id(socketHolder.getId()));
            }
        });

        repeater.setRight(new TargetDelayedStreamChannel(()->{
            try {
                Socket socket = new Socket(targetHost, targetPort);
                System.out.println("获取到目标主机的连接");
                return socket;
            } catch (IOException e) {
                System.out.println("未获取目标主机的连接");
                return null;
            }
        }));

        repeater.startLeftToRight();

        super.add(socketHolder);

    }

    public boolean recycle(String id) {

        Channel holder = getById(id);
        if (holder == null) {
            return false;
        }
        Channel right = holder.getRepeater().getRight();
        if (right != null) {
            right.close(true);
        }

        return true;
    }

}
